package controller;

import java.io.FileInputStream;
import javafx.collections.ObservableList;
import javafx.scene.SnapshotParameters;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.control.*;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.*;
import java.util.ArrayList;

public class MediaController {
    public void initialize() {
//        rootPane.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
//            @Override
//            public void handle(MouseEvent event) {
//                playListMenuBox.setVisible(false);
//                playListPane.setVisible(false);
//            }
//        });

        // new Image(getClass().getResourceAsStream("file:icons/play.png"));
        //URL playURL = MediaController.class.getResource("/icons/play.png");
        //Image playBtnImg = new Image(playURL.toString());
        //ImageView playBtnImgView = new ImageView(playBtnImg);
        //playBtnImgView.setFitHeight(40);
        //playBtnImgView.setFitWidth(40);
        //playButton.setGraphic(playBtnImgView);
        initialRoundShadowImg(recommendCover1);
        initialRoundShadowImg(recommendCover2);
        initialRoundShadowImg(recommendCover3);
        initialRoundShadowImg(recommendCover4);

        readCacheFromDAT();
        addPlayListListViewEventListener();
        checkUserInfo();
        setUserCollection();
    }

    // ------------------------------------UI初始化------------------------------------
    public ImageView recommendCover1;
    public ImageView recommendCover2;
    public ImageView recommendCover3;
    public ImageView recommendCover4;

    public AnchorPane rootPane;
    public Pane recommendView;
    private void initialRoundShadowImg(ImageView imageView){
        Rectangle clip = new Rectangle(
                imageView.getFitWidth(), imageView.getFitHeight()
        );
        clip.setArcWidth(8);
        clip.setArcHeight(8);
        imageView.setClip(clip);
        // snapshot the rounded image.
        SnapshotParameters parameters = new SnapshotParameters();
        parameters.setFill(Color.TRANSPARENT);
        WritableImage image = imageView.snapshot(parameters, null);
        // remove the rounding clip so that our effect can show through.
        imageView.setClip(null);
        // apply a shadow effect.
        imageView.setEffect(new DropShadow(10, Color.GRAY));
        // store the rounded image in the imageView.
        imageView.setImage(image);
    }

    // ------------------------------------界面切换------------------------------------
    private void setAllViewDisable(){
        recommendView.setVisible(false);
        listDetailView.setVisible(false);

        listMusicListView.getItems().clear();
    }

    public void onRecommendButton(){
        setAllViewDisable();
        recommendView.setVisible(true);
    }

    public void onUserFavorMusicButton(){
        if(!isLoginIn){
            onOpenUserInfoButton();
            return;
        }

        try{
            MusicTransferClient client = new MusicTransferClient("UL\t"+userId);
            // 等待服务器返回数据
            while (client.getProgress()==0) { System.out.print("");}

            String _listId=client.getULLID();
            onListDetailViewEnable(new CollectionInfo(_listId,"我喜欢的"));
        }catch (Exception ignored){ }
    }

    // 歌单按钮设置
    public void onListButton1(){
        onListDetailViewEnable(new CollectionInfo("1","运气来得若有似无"));
    }
    public void onListButton2(){
        onListDetailViewEnable(new CollectionInfo("2","1989"));
    }
    public void onListButton3(){
        onListDetailViewEnable(new CollectionInfo("3","想去海边"));
    }
    public void onListButton4(){
        onListDetailViewEnable(new CollectionInfo("4","柔软"));
    }
    public void onListButton5(){
        onListDetailViewEnable(new CollectionInfo("5","乐队|国内宝藏乐队合集！"));
    }
    public void onListButton6(){
        onListDetailViewEnable(new CollectionInfo("6","90年代美国经典电影主题曲"));
    }
    public void onListButton7(){
        onListDetailViewEnable(new CollectionInfo("7","[经典华语]老歌永远不过时"));
    }
    public void onListButton8(){
        onListDetailViewEnable(new CollectionInfo("8","Billboard热单排行榜"));
    }

    // 推荐歌曲
    public void onRecommendMusicButton1(){
        setPlayListIndex(addMusicToPlayList("12"));
    }
    public void onRecommendMusicButton2(){
        setPlayListIndex(addMusicToPlayList("4"));
    }
    public void onRecommendMusicButton3(){
        setPlayListIndex(addMusicToPlayList("17"));
    }
    public void onRecommendMusicButton4(){
        setPlayListIndex(addMusicToPlayList("25"));
    }
    public void onRecommendMusicButton5(){
        setPlayListIndex(addMusicToPlayList("31"));
    }
    public void onRecommendMusicButton6(){
        setPlayListIndex(addMusicToPlayList("2"));
    }
    public void onRecommendMusicButton7(){
        setPlayListIndex(addMusicToPlayList("35"));
    }
    public void onRecommendMusicButton8(){
        setPlayListIndex(addMusicToPlayList("9"));
    }
    public void onRecommendMusicButton9(){
        setPlayListIndex(addMusicToPlayList("39"));
    }
    public void onRecommendMusicButton10(){
        setPlayListIndex(addMusicToPlayList("38"));
    }

    // ------------------------------------media controller------------------------------------
    public ImageView exitButton;
    public ImageView playButton;
    public ImageView pauseButton;
    public Slider volumeSlider;
    public Slider progressSlider;
    public Label maxTimeLabel;
    public Label curTimeLabel;
    public ImageView switchNextButton;
    public ImageView switchLastButton;
    public ImageView coverButton;
    public Pane musicDetailPane;
    public Pane errorPane;

    private double maxTime, curTime;
    private MediaPlayer mediaPlayer;


    // ------------------------------------音乐控制器 （footer）------------------------------------
    public void onPlayButton() {
        if (mediaPlayer != null && playList.size() != 0) {
            mediaPlayer.play();
            pauseButton.setVisible(true);
            playButton.setVisible(false);
        }
    }

    public void onPauseButton() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            playButton.setVisible(true);
            pauseButton.setVisible(false);
        }
    }

    public void onProgressSliderMouseDragged(MouseEvent event) {
        onProgressSliderMoved(event);
    }

    public void onProgressSliderMousePressed(MouseEvent event) {
        onProgressSliderMoved(event);
    }

    /*
    public void onProgressSliderMouseReleased(MouseEvent event) {
        onProgressSliderMoved(event);
    }

     */

    private void onProgressSliderMoved(MouseEvent event) {
        if (mediaPlayer != null) {
            progressSlider.setValueChanging(true);
            double value = (event.getX() / progressSlider.getWidth()) * progressSlider.getMax();
            progressSlider.setValue(value);
            mediaPlayer.seek(mediaPlayer.getTotalDuration().multiply(progressSlider.getValue() / 100));
            progressSlider.setValueChanging(false);
        } else {
            progressSlider.setValue(0);
        }
    }

    public void onSwitchLastButton() {
        if (mediaPlayer != null && playList.size() != 0) {
            switch (playMode) {
                case 0:
                    setPlayListIndex(playListIndex - 1);
                    break;
                case 1:
                    setPlayListIndex(playListIndex);
                    break;
                case 2:
                    setPlayListIndex((int) (Math.random() * playList.size()));
                    break;
            }
        }
    }

    public void onSwitchNextButton() {
        if (mediaPlayer != null && playList.size() != 0){
            switch (playMode) {
                case 0:
                    setPlayListIndex(playListIndex + 1);
                    break;
                case 1:
                    setPlayListIndex(playListIndex);
                    break;
                case 2:
                    setPlayListIndex((int) (Math.random() * playList.size()));
                    break;
            }
        }
    }

    public void onCoverButton(){
        musicDetailPane.setVisible(!musicDetailPane.isVisible());
    }

    public Label musicNameLabel;
    public Label artistNameLabel;
    private void updateMusicInfo(){
        if(playList.size()>0){
            MusicInfo info=(MusicInfo) playListListView.getItems().get(playListIndex);
            musicNameLabel.setText(info.getName());
            artistNameLabel.setText(info.getArtist());
        }else{
            musicNameLabel.setText("");
            artistNameLabel.setText("");
        }
    }

    // 播放模式处理
    private final Image[] playModeImage={
            new Image("file:src/main/resources/icons/sequence.png"), //列表循环
            new Image("file:src/main/resources/icons/loop.png"), //单曲循环
            new Image("file:src/main/resources/icons/random.png") //随机播放
    };
    public ImageView playModeButton;
    private int playMode = 0;
    public void onPlayModeButton(){
        playMode=(playMode+1)%(playModeImage.length);
        playModeButton.setImage(playModeImage[playMode]);
    }

    private void onEndOfMedia() {
        switch (playMode) {
            case 0:
                setPlayListIndex(playListIndex + 1);
                break;
            case 1:
                setPlayListIndex(playListIndex);
                break;
            case 2:
                setPlayListIndex((int) (Math.random() * playList.size()));
                break;
        }
    }

    // ------------------------------------当前播放列表------------------------------------
    private ArrayList<Media> playList = new ArrayList<>();
    private int playListIndex = 0;
    // playlist controller
    public ImageView playListButton;
    public Pane playListPane;
    public ListView playListListView;
    public ContextMenu playListContextMenu;

    // 播放列表控制器
    private void addPlayListListViewEventListener(){
        playListListView.setCellFactory(lv -> {
            ListCell<MusicInfo> cell = new ListCell<>() {
                @Override
                protected void updateItem(MusicInfo item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setText(null);
                    } else {
                        setText(item.toString());
                    }
                }
            };
            cell.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
                if (event.getButton()== MouseButton.PRIMARY && (! cell.isEmpty())) {
                    if (event.getClickCount() == 2) {
                        playListIndex = playListListView.getSelectionModel().getSelectedIndex();
                        if(playListIndex!=-1) startMediaPlayer();
                    }
                }
            });
            return cell ;
        });
    }

    public void onPlayListButton() {
        playListPane.setVisible(!playListPane.isVisible());
    }

    public void onPlayListPlayButton() {
        playListIndex=playListListView.getSelectionModel().getSelectedIndex();
        startMediaPlayer();
    }

    public void onPlayListFavorButton(){
        MusicInfo musicInfo=(MusicInfo) playListListView.getSelectionModel().getSelectedItem();
        favorMusic(musicInfo.getId());
    }

    public void onPlayListRemoveButton() {
        int index = playListListView.getSelectionModel().getSelectedIndex();
        playList.remove(index);
        playListListView.getItems().remove(index);
        //System.out.println(playList.size());
        if (playList.size() == 0) {
            if (mediaPlayer != null) {
                onPauseButton();
                mediaPlayer.stop();
            }
            updateMusicInfo();
        } else {
            setPlayListIndex(playListIndex-1);
        }
        updateListTitleLabel();
    }

    public void onPlayListContextMenuShown() {
        if (playListListView.getSelectionModel().getSelectedItem() == null) {
            try {
                playListContextMenu.hide();
            } catch (NullPointerException e) {
                // 肯定会报错，但是能正常运行，所以不管了
            }
        }
    }

    private void setPlayListIndex(int index){
        //System.out.println(index);
        playListIndex = index % playList.size();
        playListListView.getSelectionModel().select(playListIndex);
        startMediaPlayer();
    }

    private void updateListTitleLabel(){
        playListTitleLabel.setText("播放列表 ("+playList.size()+")");
    }

    public Label playListTitleLabel;
    private String tempName="",tempArtist="";
    private int addMusicToPlayList(String id){
        Media _media=null;
        boolean isExist=false;

        // 在缓存表中查找歌曲
        for(CacheInfo info:cacheInfos){
            if(info.id.equals(id)){
                tempName=info.name;
                tempArtist=info.artist;

                File file=new File("src/main/resources/temp/m"+id+".tmp");
                String fileStr = file.toURI().toString();
                _media=new Media(fileStr);

                isExist=true;
                break;
            }
        }

        if(!isExist){
            // 从server获取歌曲
            _media = getMusicFromServer(id);
        }

        if(_media!=null){
            // 添加到播放列表
            ObservableList<MusicInfo> musicInfos=playListListView.getItems();
            for(int i=0;i<musicInfos.size();i++){
                if(musicInfos.get(i).getId().equals(id)) return i;
            }

            playList.add(_media);
            playListListView.getItems().add(new MusicInfo(id,tempName,tempArtist));
            updateListTitleLabel();
            return playList.size()-1;
        }

        return playListIndex;
    }

    private void clearPlayList(){
        playList.clear();
        playListListView.getItems().clear();
        playListIndex=0;
        if (mediaPlayer != null) {
            onPauseButton();
            mediaPlayer.stop();
        }
    }

    // ------------------------------------歌曲缓存管理------------------------------------
    private class CacheInfo{
        public String id;
        public String name;
        public String artist;
        public CacheInfo(String[] _info){
            id=_info[0];
            name=_info[1];
            artist=_info[2];
        }
    }
    private ArrayList<CacheInfo> cacheInfos=new ArrayList<>();
    private void readCacheFromDAT(){
        String datFilePath="src/main/resources/cache/cache.dat";
        BufferedReader reader;
        try{
            FileInputStream fileInputStream=new FileInputStream(datFilePath);
            InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream);
            reader=new BufferedReader(inputStreamReader);
            String tempStr;
            while((tempStr=reader.readLine())!=null){
                String[] info=tempStr.split("\t");
                cacheInfos.add(new CacheInfo(info));
            }
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    private Media getMusicFromServer(String _id) {
        try{
            MusicTransferClient client=new MusicTransferClient("M\t"+_id);
            // 等待服务器返回数据
            while(client.getProgress()==0) {System.out.print(""); }
            String[] infos=client.getMusicInfo();

            String _name=infos[1],_artist=infos[2];

            // 添加到缓存表
            BufferedWriter writer;
            File cacheFile=new File("src/main/resources/cache/cache.dat");
            writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(cacheFile,true)));
            writer.write(_id+"\t"+_name+"\t"+_artist+"\n");
            writer.close();

            cacheInfos.add(new CacheInfo(new String[]{_id,_name,_artist}));

            // 获取音频文件
            File musicFile=new File("src/main/resources/temp/m"+_id+".tmp");
            String fileStr = musicFile.toURI().toString();
            tempName=_name;
            tempArtist=_artist;
            return new Media(fileStr);
        }catch (Exception ex){
            return null;
        }
    }

    // ------------------------------------窗口事件------------------------------------

    //处理窗口偏移的变量
    private double xOffset;
    private double yOffset;
    //结束应用
    public void onExitButton(){
        Stage stage = (Stage)rootPane.getScene().getWindow();
        stage.close();
    }

    //最小化应用
    public void onMinimizeButton(){
        Stage stage = (Stage)rootPane.getScene().getWindow();
        stage.setIconified(true);
    }

    //处理拖拽窗口事件
    public void onHeaderPanePressed(MouseEvent event){
        event.consume();
        xOffset = event.getSceneX();
        yOffset = event.getSceneY();
    }
    public void onHeaderPaneDragged(MouseEvent event){
        event.consume();
        Stage stage = (Stage)rootPane.getScene().getWindow();
        stage.setX(event.getScreenX() - xOffset);
        stage.setY(event.getScreenY() - yOffset);
    }

    // ------------------------------------歌词显示页面------------------------------------
    public VBox lyricsVBox;
    public ScrollPane lyricsScrollPane;

    // 存储歌词数据
    private class Lyrics{
        public int timelineMin;
        public int timelineSec;
        public String lyric;
        public Lyrics(String _info){
            String[] _infos=_info.split("]");
            timelineMin=Integer.parseInt(_infos[0].substring(1,3));
            timelineSec=Integer.parseInt(_infos[0].substring(4,6));
            if(_infos.length>1) lyric=_infos[1];
            else lyric=" ";
            // System.out.println(timelineMin+":"+timelineSec+"\t"+lyric);
        }
    }
    private ArrayList<Lyrics> lyrics=new ArrayList<>();
    private int lyricsLength=0;

    // 读取一首歌的全部歌词数据
    private void initLyrics(String _id){
        try{
            String lyricsFilePath="src/main/resources/temp/l"+_id+".tmp";
            // 变量初始化
            lyricsLength=0;
            lyrics.clear();

            BufferedReader reader;
            FileInputStream fileInputStream=new FileInputStream(lyricsFilePath);
            InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream);
            reader=new BufferedReader(inputStreamReader);
            String tempStr;
            while((tempStr=reader.readLine())!=null){
                Lyrics tempLyrics=new Lyrics(tempStr);
                lyrics.add(tempLyrics);
                lyricsLength++;

                addLyricsToVBox(tempLyrics);
            }
        }catch (IOException ignored){ }

        preLyricsIndex=-1;
    }
    private void addLyricsToVBox(Lyrics _lyrics){
        Label lyricsLabel=new Label(_lyrics.lyric);
        lyricsLabel.setId("lyrics");
        lyricsVBox.getChildren().add(lyricsLabel);
    }

    // 更新歌词
    private int preLyricsIndex=-1;
    private void updateLyrics(double _timeline){
        try{
            int curIndex=0;
            for(int i=0;i<lyricsLength;i++){
                Lyrics curLyrics=lyrics.get(i);
                if(_timeline>=curLyrics.timelineMin*60+curLyrics.timelineSec){
                    curIndex=i;
                }
            }

            // 当歌词换行才进行强制滚动
            if(preLyricsIndex!=curIndex){
                for(int i=0;i<lyricsLength;i++)
                    lyricsVBox.getChildren().get(i).setId("lyrics");

                Label curLabel=(Label) lyricsVBox.getChildren().get(curIndex);
                curLabel.setId("lyrics-playing");

                double h=lyricsScrollPane.getContent().getBoundsInLocal().getHeight();
                double y=(curLabel.getBoundsInParent().getMaxY()+curLabel.getBoundsInParent().getMinY())/2.0;
                double v=lyricsScrollPane.getViewportBounds().getHeight();

                double scrollValue=(y-0.5*v)/(h-v);
                if(scrollValue<0)scrollValue=0;
                else if(scrollValue>1)scrollValue=1;
                lyricsScrollPane.setVvalue(scrollValue);

                preLyricsIndex=curIndex;
            }
        }catch (Exception ignored){ }
    }

    public void onCloseDetailButton(){
        musicDetailPane.setVisible(false);
    }

    // ------------------------------------歌单详情页面------------------------------------
    public Pane listDetailView;
    public ListView listMusicListView;
    public ImageView listCoverImage;
    public ImageView listFavorButton;
    public ImageView listFavored;
    public Label listNameLabel;
    private CollectionInfo tempListInfo;

    private void onListDetailViewEnable(CollectionInfo info) {
        listFavorButton.setVisible(true);

        setAllViewDisable();
        listDetailView.setVisible(true);
        MusicInfo[] musicInfos = getMusicInfoOfList(info.getId());
        if (musicInfos != null) {
            for (MusicInfo musicInfo : musicInfos) {
                listMusicListView.getItems().add(musicInfo);
            }
        }

        String _id=info.getId();
        if(!_id.equals("1")&&!_id.equals("2")&&!_id.equals("3")&&!_id.equals("4")&&
                !_id.equals("5")&&!_id.equals("6")&&!_id.equals("7")&&!_id.equals("8")){
            listCoverImage.setImage(new Image("file:src/main/resources/covers/myFavListCover.png"));
            listFavorButton.setVisible(false);

            listNameLabel.setText(info.getName());
            tempListInfo=info;
        }else{
            // 获取歌单信息
            try{
                listNameLabel.setText(info.getName());

                listCoverImage.setImage(new Image("file:src/main/resources/temp/c"+info.getId()+".tmp"));
                tempListInfo=info;

                // 是否允许用户收藏
                if(isUserFavorList(info.getId())) {
                    listFavored.setVisible(true);
                    listFavorButton.setVisible(false);
                }
                else {
                    listFavored.setVisible(false);
                    listFavorButton.setVisible(true);
                }
            }catch (Exception ignored) {  }
        }
    }

    private MusicInfo[] getMusicInfoOfList(String _listId){
//        //debug
//
//        return new MusicInfo[]{
//                new MusicInfo("13","Welcome to New York","Taylor Swift"),
//                new MusicInfo("22","白","房东的猫")
//        };

        try{
            MusicTransferClient client = new MusicTransferClient("L\t"+_listId);
            // 等待服务器返回数据
            while (client.getProgress()==0) { System.out.print("");}
            String[] infos = client.getListInfo().split("\n");

            ArrayList<MusicInfo> musicInfos=new ArrayList<>();
            for (String info : infos) {
                String[] s=info.split("\t");
                musicInfos.add(new MusicInfo(s[0],s[1],s[2]));
            }

            return musicInfos.toArray(new MusicInfo[musicInfos.size()]);
        }catch(Exception ex){
            return null;
        }

    }

    public void onListMusicListViewClicked(MouseEvent event){
        if (event.getButton() == MouseButton.PRIMARY) {
            if (event.getClickCount() == 2) {
                MusicInfo musicInfo=(MusicInfo) listMusicListView.getSelectionModel().getSelectedItem();
                setPlayListIndex(addMusicToPlayList(musicInfo.getId()));
                startMediaPlayer();
            }
        }
        playListPane.setVisible(false);
    }

    public void onListMusicPlayButton(){
        MusicInfo musicInfo=(MusicInfo) listMusicListView.getSelectionModel().getSelectedItem();
        setPlayListIndex(addMusicToPlayList(musicInfo.getId()));
        startMediaPlayer();
    }

    public void onListMusicFavorButton(){
        MusicInfo musicInfo=(MusicInfo) listMusicListView.getSelectionModel().getSelectedItem();
        favorMusic(musicInfo.getId());
    }

    public void onListPlayAllButton(){
        clearPlayList();

        ObservableList<MusicInfo> musicInfos=listMusicListView.getItems();
        for(MusicInfo musicInfo:musicInfos){
            addMusicToPlayList(musicInfo.getId());
        }

        setPlayListIndex(0);
    }

    public void onListFavorButton(){
        if(!isLoginIn){
            onOpenUserInfoButton();
            return;
        }
        try{
            MusicTransferClient client = new MusicTransferClient("FL\t"+userId+"\t"+tempListInfo.getId());
            // 等待服务器返回消息
            while (client.getProgress()==0) { System.out.print("");}

            if(client.getProgress()==-1){
                throw new Exception();
            }

            myCollectionListView.getItems().add(tempListInfo);
            listFavored.setVisible(true);
            listFavorButton.setVisible(false);

        }catch (Exception ex){
            System.out.println("收藏失败");
        }
    }

    private boolean isUserFavorList(String _listId){
        ObservableList<CollectionInfo> infos=myCollectionListView.getItems();

        for(CollectionInfo info:infos){
            if(info.getId().equals(_listId)) return true;
        }
        return false;
    }

    // ------------------------------------用户信息------------------------------------
    public Pane signPane;
    public Pane loginPane;
    public Pane registerPane;

    public void onOpenUserInfoButton(){
        if(!isLoginIn){
            signPane.setVisible(true);
        }
    }

    // 界面切换
    public void onCloseSignPaneButton(){
        loginPane.setVisible(true);
        registerPane.setVisible(false);
        signPane.setVisible(false);
        loginErrorPane.setVisible(false);
        regErrorPane.setVisible(false);
    }
    public void onRegisterLabel(){
        loginPane.setVisible(false);
        registerPane.setVisible(true);
    }
    public void onLoginLabel(){
        loginPane.setVisible(true);
        registerPane.setVisible(false);
    }

    // 用户信息缓存
    private boolean isLoginIn=false;
    private String userId=null;

    private void checkUserInfo(){
        String datFilePath="src/main/resources/cache/user.dat";
        BufferedReader reader;
        try{
            FileInputStream fileInputStream=new FileInputStream(datFilePath);
            InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream);
            reader=new BufferedReader(inputStreamReader);
            String tempStr=reader.readLine();

            // 文件里有内容，说明用户曾经登录过，用户信息不为空
            if(tempStr!=null){
                isLoginIn=true;
                userId=tempStr;

                tempStr=reader.readLine();
                userNameLabel.setText(tempStr);
                logoutLabel.setVisible(true);
            }
        }catch (IOException ignored){ }
    }

    public Label logoutLabel;
    public void onLogoutLabel(){
        if(isLoginIn) logout();
    }
    private void logout(){
        BufferedWriter writer;
        File cacheFile=new File("src/main/resources/cache/user.dat");
        try{
            writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(cacheFile,false)));
            writer.write("");
            writer.close();

            userId=null;
            userNameLabel.setText("未登录");
            isLoginIn=false;
            listFavored.setVisible(false);
            listFavorButton.setVisible(true);
            setUserCollection();
            logoutLabel.setVisible(false);
        }catch (IOException ignored){ }
    }

    // 登陆注册通信
    public TextField loginUserIdText;
    public PasswordField loginPswText;
    public TextField regUserIdText;
    public TextField regUserNameText;
    public PasswordField regPswText;
    public PasswordField regPswCheckText;
    public Pane loginErrorPane;
    public Pane regErrorPane;
    public Label regErrorLabel;

    public Label userNameLabel;

    public void onLoginButton(){
        loginErrorPane.setVisible(false);
        boolean _isLogin = login(loginUserIdText.getText(),loginPswText.getText());
        if(_isLogin){
            onCloseSignPaneButton();
            setUserCollection();

            if(tempListInfo!=null) {
                // 当用户处于歌单界面，进行判断
                if (isUserFavorList(tempListInfo.getId())) {
                    listFavored.setVisible(true);
                    listFavorButton.setVisible(false);
                }
            }

            logoutLabel.setVisible(true);
            isLoginIn=true;
        }else{
            loginErrorPane.setVisible(true);
        }
    }
    public void onRegisterButton(){
        regErrorPane.setVisible(false);
        if(!regPswText.getText().equals(regPswCheckText.getText())){
            regErrorLabel.setText("两次输入的密码不一致！");
            regErrorPane.setVisible(true);
            return;
        }
        boolean isRegister = register(regUserIdText.getText(),regUserNameText.getText(),regPswText.getText());
        if(isRegister){
            onLoginLabel();
        }else{
            regErrorLabel.setText("用户已存在！");
            regErrorPane.setVisible(true);
        }
    }

    private boolean login(String _userId,String _psw){
        try{
            MusicTransferClient client = new MusicTransferClient("I\t"+_userId+"\t"+_psw);
            // 等待服务器返回消息
            while (client.getProgress()==0) { System.out.print("");}

            if(client.getProgress()==-1) {
                System.out.println("登录失败");
                return false;
            }

            // 成功登录
            userNameLabel.setText(client.getUserName()); //用户名
            userId=_userId;

            // 存进用户缓存
            BufferedWriter writer;
            File cacheFile=new File("src/main/resources/cache/user.dat");
            try{
                writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(cacheFile,false)));
                writer.write(_userId+"\n"+client.getUserName());
                writer.close();
            }catch (IOException ignored){ }

            return true;
        }catch (Exception ex){
            return false;
        }
    }

    private boolean register(String _userId,String _userName,String _psw){

        try{
            MusicTransferClient client = new MusicTransferClient("U\t"+_userId+"\t"+_psw+"\t"+_userName);
            // 等待服务器返回消息
            while (client.getProgress()==0) {System.out.print(""); }

            return client.getProgress() == 1;
        }catch (Exception ex){
            return false;
        }
    }

    private void favorMusic(String _id){
        if(!isLoginIn) {
            signPane.setVisible(true);
        }else{
            try{
                MusicTransferClient client = new MusicTransferClient("F\t"+userId+"\t"+_id);
                // 等待服务器返回消息
                while (client.getProgress()==0) { System.out.print("");}

                if(client.getProgress()==-1){
                    throw new Exception();
                }
            }catch (Exception ex){
                System.out.println("收藏失败");
            }
        }
    }

    // ----------------------------------用户歌单管理----------------------------------
    public ListView myCollectionListView;

    private void setUserCollection(){
        if(userId==null) {
            myCollectionListView.getItems().clear();
            return;
        }

        try{
            MusicTransferClient client = new MusicTransferClient("UF\t"+userId);
            // 等待服务器返回消息
            while (client.getProgress()==0) { System.out.print("");}

            if(client.getProgress()==-1){
                throw new Exception();
            }

            myCollectionListView.getItems().clear();

            String[] infos = client.getLists().split("\n");

            for (String info : infos) {
                String[] s=info.split("\t");
                myCollectionListView.getItems().add(new CollectionInfo(s[0],s[1]));
            }

        }catch (Exception ignored){ }

        // 添加事件处理
        myCollectionListView.setCellFactory(lv -> {
            ListCell<CollectionInfo> cell = new ListCell<>() {
                @Override
                protected void updateItem(CollectionInfo item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setText(null);
                    } else {
                        setText(item.toString());
                    }
                }
            };
            cell.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
                if (event.getButton()== MouseButton.PRIMARY && (! cell.isEmpty())) {
                    CollectionInfo item = cell.getItem();
                    onListDetailViewEnable(item);
                }
            });
            return cell ;
        });
    }

    // ------------------------------------总控函数------------------------------------
    private class MusicInfo{
        private String _id,_name,_artist;
        public MusicInfo(String _id,String _name,String _artist){
            this._id=_id; this._name=_name; this._artist=_artist;
        }
        public String getId(){
            return _id;
        }
        public String getName(){
            return _name;
        }
        public String getArtist(){
            return _artist;
        }
        public String toString(){
            return _name+" - "+_artist;
        }
    }
    private class CollectionInfo{
        private String _id,_name;
        public CollectionInfo(String _id,String _name){
            this._id=_id; this._name=_name;
        }
        public String getId(){ return _id; }
        public String getName(){ return _name; }
        public String toString(){ return _name; }
    }

    private void startMediaPlayer() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }

        updateMusicInfo();

        // 解析为MediaPlayer
        Media media = playList.get(playListIndex);
        mediaPlayer = new MediaPlayer(media);

        // 音量绑定
        mediaPlayer.volumeProperty().bind(volumeSlider.valueProperty().divide(100));
        // before播放
        mediaPlayer.setOnReady(() -> {
            maxTime = mediaPlayer.getStopTime().toSeconds();
            maxTimeLabel.setText(doubleSecond2String(mediaPlayer.getTotalDuration().toSeconds()));

            lyricsVBox.getChildren().clear();

            MusicInfo musicInfo=(MusicInfo) playListListView.getItems().get(playListIndex);
            initLyrics(musicInfo.getId());
        });
        // after播放
        mediaPlayer.setOnEndOfMedia(() -> {
            mediaPlayer.stop();
            mediaPlayer.seek(Duration.ZERO);
            // System.out.println("touch the end of media");
            onEndOfMedia();
        });
        // 进度条绑定
        mediaPlayer.currentTimeProperty().addListener(ov -> {
            curTime = mediaPlayer.getCurrentTime().toSeconds();
            updateLyrics(curTime);
            curTimeLabel.setText(doubleSecond2String(curTime));
            if (!progressSlider.isValueChanging())
                progressSlider.setValue(curTime / maxTime * 100);
        });
        onPlayButton();
    }
    private String doubleSecond2String(double second) {
        int _second = (int) second;
        return String.format("%02d:%02d", _second / 60, _second % 60);
    }
}
